"use strict"

export class apducmd{
    public CLA: number;
    public INS: number;
    public P1: number;
    public P2: number;
    public LC: number;
    public DATA: Buffer;
    public LE: number;
    public EXT: boolean;

    public constructor(){

    }

    public parse(cmd: Buffer){
        let cmdlen = cmd.length;
        this.CLA = cmd[0];
        this.INS = cmd[1];
        this.P1 = cmd[2];
        this.P2 = cmd[3];
        this.LC = 0;
        this.LE = undefined;
        this.DATA = new Buffer(0);
        this.EXT = false;

        if(cmdlen == 4)         // cla ins p1 p2
            return;
        if(cmdlen == 5){        // cla ins p1 p2 le
            this.LE = cmd[4];
            if(cmd[4] == 0)
                this.LE = 0xff;
        }
        else if(cmd[4] != 0 && (cmd[4]+5) == cmdlen){ // cla ins p1 p2 lc data
            this.LC = cmd[4];
            this.DATA = new Buffer(this.LC);
            cmd.slice(5).copy(this.DATA);
        }
        else if(cmd[4] != 0 && (cmd[4]+6) == cmdlen){ // cla ins p1 p2 lc data le
            this.LC = cmd[4];
            this.DATA = new Buffer(this.LC);
            cmd.slice(5).copy(this.DATA);
            this.LE = cmd[this.LC=5];
            if(this.LE == 0)
                this.LE = 256;
        }
        else if(cmd[4] == 0 && cmdlen == 7){    // cla ins p1 p2 00 le1 le2
            this.LE = cmd.readUInt16BE(5);
            if(this.LE == 0)
                this.LE = 65536;
            this.EXT = true;
        }                                           // cla ins p1 p2 00 lc1 lc2 data
        else if(cmdlen > 7 && cmd[4] == 0 && (cmd.readUInt16BE(5)+7) == cmdlen){
            this.LC = cmd.readUInt16BE(5);
            this.DATA = new Buffer(this.LC);
            cmd.slice(7, 7+this.LC).copy(this.DATA);
            this.EXT = true;
        }                                           // cla ins p1 p2 00 lc1 lc2 data le1 le2
        else if(cmdlen > 9 && cmd[4] == 0 && (cmd.readUInt16BE(5)+9) == cmdlen){
            this.LC = cmd.readUInt16BE(5);
            this.DATA = new Buffer(this.LC);
            cmd.slice(7, 7+this.LC).copy(this.DATA);
            this.LE = cmd.readUInt16BE(this.LC+7);
            if(this.LE == 0)
                this.LE = 65536;
            this.EXT = true;
        }
    }

}


